import { EllipsisOutlined, PlusOutlined } from '@ant-design/icons';
import { ActionType, ProCard, ProColumns, EditableProTable, ProFormField, } from '@ant-design/pro-components';
import { ProTable, TableDropdown } from '@ant-design/pro-components';
import { Button, ConfigProvider, Dropdown, Form, Input, Space, Tag, message } from 'antd';
import { TyThaliConfigItemItem, TableListPagination } from './data';
import type { InputRef } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { reqTyBaseFormulaDetailList, reqDeleteTyBaseFormulaDetail } from '@/services/tybaseformuladetail';
import { reqTyHerbList } from '@/services/tyherb';

const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};
const TagList: React.FC<{
  value?: {
    key: string;
    label: string;
  }[];
  onChange?: (
    value: {
      key: string;
      label: string;
    }[],
  ) => void;
}> = ({ value, onChange }) => {
  const ref = useRef<InputRef | null>(null);
  const [newTags, setNewTags] = useState<
    {
      key: string;
      label: string;
    }[]
  >([]);
  const [inputValue, setInputValue] = useState<string>('');

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setInputValue(e.target.value);
  };

  const handleInputConfirm = () => {
    let tempsTags = [...(value || [])];
    if (
      inputValue &&
      tempsTags.filter((tag) => tag.label === inputValue).length === 0
    ) {
      tempsTags = [
        ...tempsTags,
        { key: `new-${tempsTags.length}`, label: inputValue },
      ];
    }
    onChange?.(tempsTags);
    setNewTags([]);
    setInputValue('');
  };

  return (
    <Space>
      {(value || []).concat(newTags).map((item) => (
        <Tag key={item.key}>{item.label}</Tag>
      ))}
      <Input
        ref={ref}
        type="text"
        size="small"
        style={{ width: 78 }}
        value={inputValue}
        onChange={handleInputChange}
        onBlur={handleInputConfirm}
        onPressEnter={handleInputConfirm}
      />
    </Space>
  );
};

const TyBaseFormulaDetailTable = ({ row, onDataItems }) => {
  const actionRef = useRef<any>();
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [dataSource, setDataSource] = useState<readonly TyThaliConfigItemItem[]>([]);
  const [form] = Form.useForm();
  const [open, setOpen] = useState(false);
  const [type, setType] = useState('table');
  const [isOpen, setIsOpen] = useState<boolean>(false);
  const [iscreated, setIscreated] = useState(true);
  const PopconfirmTitle = `确认删除吗？此操作不可撤销 `;
  const handleModal = (show: boolean, row: any = null) => {
    setIsOpen(show);
  }

  const [enumList, setEnumList] = useState<any>({});

  const handleDelete = async (id: number) => {
    // const res = await reqDeleteTyThaliConfigItem({ id })
    // if (res?.resultCode === '00000000') {
    // 	message.success(res?.message)
    // 	actionRef?.current.reload()
    // }
  }

  const handleCreate = (row: any) => {
  }

  const handleChange = (items: any) => {
    let dataItems: any = [];
    items.map((item: any) => {
      let { id, index, createrId, delFlag, gmtCreate, gmtModify, lastModifyId, ...tmpItem } = item
      // debugger;
      if (enumList) {
        Object.assign(tmpItem, { "tyHerbName": enumList[item?.tyHerbId]?.text });
      }
      dataItems.push(tmpItem);
    });
    setDataSource(items);
    onDataItems(dataItems);
  }

  const initData = async () => {
    const formulaRes = await reqTyHerbList({ "pageSize": 100 })
    if (formulaRes?.resultCode === '00000000') {
      const { result } = formulaRes?.data;

      let items: any = {};
      result?.map((item: any) => {
        Object.assign(items, { [item?.id]: { "text": item?.name } })
      });
      setEnumList(items);
    }
  }

  useEffect(() => {
    initData()
  }, [])

  const handleTableList = async (params: TableListPagination) => {
    Object.assign(params, { "pageNum": params.current });
    Object.assign(params, { "tyBaseFormulaId": row?.id });
    const res = await reqTyBaseFormulaDetailList(params);
    if (res?.resultCode === '00000000') {
      const { result, total } = res?.data;
      return {
        data: result,
        success: true,
        total: total,
      };
    }
  };

  const columns: ProColumns<TyThaliConfigItemItem>[] = [
    {
      title: '项目名称',
      dataIndex: 'tyHerbId',
      valueType: 'select',
      valueEnum: enumList,
    },
    {
      title: '数量',
      dataIndex: 'quantity',
      ellipsis: false,
      search: false
    },
    {
      title: '操作',
      valueType: 'option',
      width: 250,
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.id);
          }}
        >
          编辑
        </a>,
        <a
          key="deletable"
          onClick={() => {
            handleChange(dataSource.filter((item) => item.id !== record.id));
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  return (
    <>
      <Space>
        <Button
          type="primary"
          onClick={() => {
            actionRef.current?.addEditRecord?.({
              id: (Math.random() * 1000000).toFixed(0),
              tyBaseFormulaId: row?.id,
              tyBaseFormulaName: row?.name
            });
          }}
          icon={<PlusOutlined />}
        >
          新建项目
        </Button>
        <Button
          key="rest"
          onClick={() => {
            form.resetFields();
          }}
        >
          重置
        </Button>
      </Space>

      <EditableProTable<TyThaliConfigItemItem>
        rowKey="id"
        // scroll={{
        //   x: 960,
        // }}
        actionRef={actionRef}
        headerTitle="明细"
        maxLength={5}
        // 关闭默认的新建按钮
        recordCreatorProps={false}
        columns={columns}
        request={(params): Promise<any> => handleTableList(params)}
        value={dataSource}
        onChange={handleChange}
        editable={{
          form,
          editableKeys,
          onSave: async (row, b, c) => {
            handleCreate(row)
          },
          onChange: setEditableRowKeys,
          actionRender: (row, config, dom) => [dom.save, dom.cancel],
        }}
      />
    </>
  )
}

export default TyBaseFormulaDetailTable;

